<template>
  <div class="channel-management">
    <div class="page-header">
      <h2>渠道管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="openAddDialog">添加渠道</el-button>
      </div>
    </div>
    
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <h3>渠道列表</h3>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="channels"
        style="width: 100%"
        border
        fit
        class="compact-table"
      >
        <el-table-column type="index" width="50" fixed="left" />
        <el-table-column label="名称" prop="name" min-width="100" />
        <el-table-column label="代码" prop="code" min-width="100" />
        <el-table-column label="描述" prop="desc" min-width="180" show-overflow-tooltip />
        <el-table-column label="图标" width="80">
          <template #default="{ row }">
            <el-image
              v-if="row.iconUrl"
              :src="row.iconUrl"
              style="width: 40px; height: 40px;"
              fit="contain"
            />
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-group">
              <el-button-group>
                <el-button
                  size="small"
                  type="primary"
                  @click="openEditDialog(row)"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  :type="row.status ? 'warning' : 'success'"
                  @click="toggleStatus(row)"
                >
                  {{ row.status ? '禁用' : '启用' }}
                </el-button>
                <el-button
                  size="small"
                  type="success"
                  @click="openPriceManagement(row)"
                >
                  价格
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(row)"
                >
                  删除
                </el-button>
              </el-button-group>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 添加渠道价格对比表 -->
    <el-card class="table-card price-comparison-card">
      <template #header>
        <div class="card-header">
          <h3>渠道价格对比</h3>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="fetchChannelPriceComparison">刷新价格</el-button>
          </div>
        </div>
      </template>
      
      <div class="price-filter compact-form">
        <el-form :inline="true" :model="priceFilterForm" size="small">
          <el-form-item label="分类">
            <el-select v-model="priceFilterForm.categoryId" placeholder="选择分类" clearable @change="fetchChannelPriceComparison">
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="关键词">
            <el-input
              v-model="priceFilterForm.keyword"
              placeholder="商品名称关键词"
              clearable
              @keyup.enter="fetchChannelPriceComparison"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchChannelPriceComparison">搜索</el-button>
            <el-button @click="resetPriceFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-table
        v-loading="priceComparisonLoading"
        :data="priceComparisonData"
        style="width: 100%"
        border
        fit
        class="compact-table"
      >
        <el-table-column type="index" width="50" fixed="left" />
        <el-table-column label="商品名称" prop="productName" min-width="120" fixed="left" />
        <el-table-column label="标准价格" prop="standardPrice" width="100" fixed="left">
          <template #default="{ row }">
            ¥{{ row.standardPrice.toFixed(2) }}
          </template>
        </el-table-column>
        
        <el-table-column 
          v-for="channel in channels" 
          :key="channel.id" 
          :label="channel.name"
          :prop="'channelPrices.' + channel.id"
          min-width="100"
        >
          <template #default="{ row }">
            <div v-if="row.channelPrices && row.channelPrices[channel.id]">
              <div class="price-value">¥{{ row.channelPrices[channel.id].toFixed(2) }}</div>
              <div class="price-diff" :class="getPriceDiffClass(row.channelPrices[channel.id] - row.standardPrice)">
                {{ (row.channelPrices[channel.id] - row.standardPrice).toFixed(2) }}
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:currentPage="pricePagination.page"
          v-model:page-size="pricePagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pricePagination.total"
          @size-change="handlePriceSizeChange"
          @current-change="handlePriceCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 渠道表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑渠道' : '添加渠道'"
      width="500px"
    >
      <el-form
        ref="channelFormRef"
        :model="channelForm"
        :rules="channelRules"
        label-width="80px"
        class="compact-form"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="channelForm.name" placeholder="请输入渠道名称" />
        </el-form-item>
        
        <el-form-item label="代码" prop="code">
          <el-input
            v-model="channelForm.code"
            placeholder="请输入渠道代码"
            :disabled="isEdit"
          />
          <div class="form-tip" v-if="isEdit">渠道代码创建后不可修改</div>
        </el-form-item>
        
        <el-form-item label="描述" prop="desc">
          <el-input
            v-model="channelForm.desc"
            placeholder="请输入渠道描述"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="图标" prop="iconUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/upload/channel-icon"
            :show-file-list="false"
            :on-success="handleIconSuccess"
            :before-upload="beforeIconUpload"
          >
            <img v-if="channelForm.iconUrl" :src="channelForm.iconUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="form-tip">建议上传正方形图片，大小不超过2MB</div>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-switch v-model="channelForm.status" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import api from '@/utils/api'

const router = useRouter()

// 加载状态
const loading = ref(false)
const submitting = ref(false)

// 渠道列表
const channels = ref([])

// 表单对话框
const dialogVisible = ref(false)
const isEdit = ref(false)
const channelFormRef = ref(null)

// 渠道表单
const channelForm = reactive({
  id: null,
  name: '',
  code: '',
  desc: '',
  iconUrl: '',
  status: true,
  sortOrder: 0
})

// 表单验证规则
const channelRules = {
  name: [
    { required: true, message: '请输入渠道名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入渠道代码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '只能包含字母、数字和下划线', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

// 获取渠道列表
const fetchChannels = async () => {
  loading.value = true
  try {
    const response = await api.get('/channels')
    if (response.data && response.data.status === 'success') {
      channels.value = response.data.data
    } else {
      ElMessage.warning('获取渠道列表失败')
    }
  } catch (error) {
    console.error('获取渠道列表失败:', error)
    ElMessage.error('获取渠道列表失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 打开添加对话框
const openAddDialog = () => {
  isEdit.value = false
  Object.assign(channelForm, {
    id: null,
    name: '',
    code: '',
    desc: '',
    iconUrl: '',
    status: true,
    sortOrder: 0
  })
  dialogVisible.value = true
  
  // 在下一个 tick 后重置表单校验结果
  setTimeout(() => {
    channelFormRef.value?.clearValidate()
  }, 0)
}

// 打开编辑对话框
const openEditDialog = (row) => {
  isEdit.value = true
  Object.assign(channelForm, {
    id: row.id,
    name: row.name,
    code: row.code,
    desc: row.desc || '',
    iconUrl: row.iconUrl || '',
    status: row.status,
    sortOrder: row.sortOrder
  })
  dialogVisible.value = true
  
  // 在下一个 tick 后重置表单校验结果
  setTimeout(() => {
    channelFormRef.value?.clearValidate()
  }, 0)
}

// 提交表单
const submitForm = async () => {
  // 表单验证
  await channelFormRef.value.validate()
  
  submitting.value = true
  try {
    let response
    
    if (isEdit.value) {
      // 编辑渠道
      response = await api.put(`/channels/${channelForm.id}`, {
        name: channelForm.name,
        desc: channelForm.desc,
        iconUrl: channelForm.iconUrl,
        status: channelForm.status,
        sortOrder: channelForm.sortOrder
      })
    } else {
      // 添加渠道
      response = await api.post('/channels', {
        name: channelForm.name,
        code: channelForm.code,
        desc: channelForm.desc,
        iconUrl: channelForm.iconUrl,
        status: channelForm.status
      })
    }
    
    if (response.data && response.data.status === 'success') {
      ElMessage.success(response.data.message || (isEdit.value ? '渠道更新成功' : '渠道添加成功'))
      dialogVisible.value = false
      fetchChannels() // 刷新列表
    } else {
      ElMessage.warning(response.data?.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
  } finally {
    submitting.value = false
  }
}

// 切换渠道状态
const toggleStatus = async (row) => {
  try {
    const response = await api.put(`/channels/${row.id}`, {
      status: !row.status
    })
    
    if (response.data && response.data.status === 'success') {
      ElMessage.success(`渠道已${row.status ? '禁用' : '启用'}`)
      fetchChannels() // 刷新列表
    } else {
      ElMessage.warning(response.data?.message || '操作失败')
    }
  } catch (error) {
    console.error('切换渠道状态失败:', error)
    ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
  }
}

// 处理删除渠道
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该渠道吗？删除后将无法恢复。',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const response = await api.delete(`/channels/${row.id}`)
        
        if (response.data && response.data.status === 'success') {
          ElMessage.success('渠道删除成功')
          fetchChannels() // 刷新列表
        } else {
          ElMessage.warning(response.data?.message || '删除失败')
        }
      } catch (error) {
        console.error('删除渠道失败:', error)
        ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
      }
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 打开价格管理页面
const openPriceManagement = (row) => {
  router.push(`/admin/channels/${row.id}/prices`)
}

// 图标上传相关
const handleIconSuccess = (response) => {
  if (response && response.status === 'success') {
    channelForm.iconUrl = response.data.url
  } else {
    ElMessage.error('上传失败')
  }
}

const beforeIconUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isJPG && !isPNG) {
    ElMessage.error('上传图标只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图标大小不能超过 2MB!')
  }
  
  return (isJPG || isPNG) && isLt2M
}

// 价格对比相关数据
const priceComparisonLoading = ref(false)
const priceComparisonData = ref([])
const categories = ref([])

// 价格筛选表单
const priceFilterForm = reactive({
  categoryId: null,
  keyword: ''
})

// 价格分页
const pricePagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 获取分类数据
const fetchCategories = async () => {
  try {
    const response = await api.get('/categories')
    if (response.data && response.data.status === 'success') {
      categories.value = response.data.data
    }
  } catch (error) {
    console.error('获取分类数据失败:', error)
  }
}

// 获取渠道价格对比数据
const fetchChannelPriceComparison = async () => {
  priceComparisonLoading.value = true
  try {
    const params = {
      page: pricePagination.page,
      pageSize: pricePagination.pageSize,
      categoryId: priceFilterForm.categoryId || undefined,
      keyword: priceFilterForm.keyword || undefined
    }
    
    const response = await api.get('/channel-price-comparison', { params })
    if (response.data && response.data.status === 'success') {
      priceComparisonData.value = response.data.data.items
      pricePagination.total = response.data.data.total
    } else {
      ElMessage.warning('获取渠道价格对比数据失败')
    }
  } catch (error) {
    console.error('获取渠道价格对比数据失败:', error)
    ElMessage.error('获取渠道价格对比数据失败: ' + (error.response?.data?.message || error.message))
  } finally {
    priceComparisonLoading.value = false
  }
}

// 重置价格筛选条件
const resetPriceFilter = () => {
  priceFilterForm.categoryId = null
  priceFilterForm.keyword = ''
  fetchChannelPriceComparison()
}

// 处理价格分页大小变化
const handlePriceSizeChange = (size) => {
  pricePagination.pageSize = size
  fetchChannelPriceComparison()
}

// 处理价格当前页变化
const handlePriceCurrentChange = (page) => {
  pricePagination.page = page
  fetchChannelPriceComparison()
}

// 获取价格差异样式
const getPriceDiffClass = (diff) => {
  if (diff > 0) return 'price-up'
  if (diff < 0) return 'price-down'
  return ''
}

// 初始化
onMounted(() => {
  fetchChannels()
  fetchCategories()
  fetchChannelPriceComparison()
})
</script>

<style scoped>
.channel-management {
  padding-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.price-comparison-card {
  margin-top: 20px;
}

.price-filter {
  margin-bottom: 20px;
}

.action-group {
  display: flex;
  justify-content: center;
}

.price-value {
  font-weight: bold;
}

.price-diff {
  font-size: 12px;
  margin-top: 3px;
}

.price-diff.higher {
  color: #f56c6c;
}

.price-diff.lower {
  color: #67c23a;
}

.price-diff.same {
  color: #909399;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.avatar-uploader {
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style> 